package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.ScheduleJobDao;
import com.baitengsoft.patentapimonitor.api.entity.ScheduleJobEntity;
import com.baitengsoft.patentapimonitor.api.model.ScheduleJobViewModel;
import com.baitengsoft.patentapimonitor.api.model.param.ScheduleJobParam;
import com.baitengsoft.patentapimonitor.api.service.ScheduleJobService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.SysParamaterUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by Admin on 2018/1/8.
 */
@Service
public class ScheduleJobServiceImpl extends BaseServiceImpl<ScheduleJobEntity> implements ScheduleJobService {
    @Autowired
    private ScheduleJobDao scheduleJobDao;

    @Resource
    SysParamaterUtil sysParamaterUtil;


    @Override
    public PageResult<ScheduleJobViewModel> searchScheduleJob(ScheduleJobParam param) {

        PageHelper.startPage(param.getPage(), param.getPageSize());
        String sql = "WHERE";
        if (StringUtils.isNotBlank(param.getPlatformName())) {
            sql += " m.platformName LIKE '%" + param.getPlatformName() + "%'";
        }
        if (StringUtils.isNotBlank(param.getStartDateStr())) {
            if (sql.indexOf("%") > 0) {
                sql += " AND m.CreateDate>='" + param.getStartDateStr() + "'";
            } else {
                sql += " m.CreateDate>='" + param.getStartDateStr() + "'";
            }

        }
        if (StringUtils.isNotBlank(param.getEndDateStr())) {
            if (sql.indexOf(">") > 0) {
                sql += " AND m.CreateDate<='" + param.getEndDateStr() + "'";
            } else {
                sql += " m.CreateDate<='" + param.getEndDateStr() + "'";
            }

        }
        if (sql.equals("WHERE")) {
            sql = "";
        }
        List<ScheduleJobViewModel> viewModels = scheduleJobDao.searchSchedule(sql);
        PageInfo<ScheduleJobViewModel> pageInfo = new PageInfo<>(viewModels);
        if (viewModels != null && viewModels.size() > 0) {
            return new PageResult<ScheduleJobViewModel>(viewModels, param.getPage(), param.getPageSize(), (int) pageInfo.getTotal());
        }
        return null;
    }

    @Override
    public Integer saveScheduleJob(ScheduleJobEntity entity) {
        return saveByNotNull(entity);
    }

    @Override
    public ScheduleJobViewModel searchSingleSchedule(int jobId) {
        return scheduleJobDao.searchSingleSchedule(jobId);
    }

    @Override
    public void processScheduleJobByIds(String idStr) {
        if (StringUtils.isNotBlank(idStr)) {
            String[] ids = idStr.split(",");
            Long[] lid = new Long[ids.length];
            StringBuilder paramStr = new StringBuilder();
            paramStr.append("[");
            for (int i = 0; i < ids.length; i++) {
                paramStr.append(Long.parseLong(ids[i]));
                if (ids.length == i + 1) continue;
                paramStr.append(",");
            }
            paramStr.append("]");
            //ResourceBundle res=ResourceBundle.getBundle("/ScheduleJob");
            //ResourceBundle res = TemplateFileUtil.getBundle("ScheduleJob");
//            String urlAndPort = res.getString("scheduleJobUrlAndPort");
//            String requestUrl = urlAndPort + "/job/schedule/run";
            String requestUrl = sysParamaterUtil.getRunQuartzJobUrl();
            post(requestUrl, paramStr.toString());
        }
    }
    /**
     * http请求，post方式
     *
     * @param strURL 请求路径
     * @param params 请求参数
     * @return 返回响应数据
     */
    public static String post(String strURL, String params) {
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                System.out.println(result);
                return result;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

}
